#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import (QDialog, QVBoxLayout,
                             QComboBox, QLineEdit, QPushButton, QLabel,
                             QDialogButtonBox,
                             QCheckBox, QGroupBox, QWidget,
                             QDateEdit, QTimeEdit, QDateTimeEdit, QButtonGroup, QRadioButton,
                             QSplitter, QListWidget, QTextEdit, QInputDialog, QMessageBox)
from PyQt5.QtCore import Qt, QDate, QTime, QDateTime
from PyQt5.QtGui import  QIntValidator, QDoubleValidator, QFont

from ui.AdvancedQueryDialog import Ui_DialogAdvancedQuery
from ui.ColumnSelectionDialog import Ui_DialogColumnSelection
from ui.RecordFormDialog import Ui_DialogRecordForm


class AdvancedQueryDialog(QDialog, Ui_DialogAdvancedQuery):
    """高级查询对话框，支持多条件组合查询"""
    
    def __init__(self, columns, parent=None, initial_conditions=None):
        """初始化高级查询对话框
        
        Args:
            columns: 列名列表
            parent: 父控件
            initial_conditions: 初始查询条件列表 [(逻辑关系, 列名, 操作符, 值), ...]
        """
        super(AdvancedQueryDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.columns = columns
        self.condition_widgets = []  # 存储所有条件行的控件
        # 转换初始条件格式，如果没有逻辑关系则默认为AND
        self.initial_conditions = []
        if initial_conditions:
            for cond in initial_conditions:
                if len(cond) == 3:  # 旧格式: (列名, 操作符, 值)
                    self.initial_conditions.append(('AND', cond[0], cond[1], cond[2]))
                elif len(cond) == 4:  # 新格式: (逻辑关系, 列名, 操作符, 值)
                    self.initial_conditions.append(cond)
        
        self.init_ui()
        
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口属性
        self.setWindowTitle("高级查询")
        
        # 连接按钮信号
        self.addBtn.clicked.connect(self.add_condition)  # 添加条件按钮
        self.clearBtn.clicked.connect(self.clear_conditions)  # 清空条件按钮
        
        # 移除设计器中的固定行控件，但保留布局结构
        self.comboBox_2.hide()
        self.comboBox_3.hide()
        self.lineEdit.hide()
        self.deleteBtn.hide()
        self.comboBox.hide()
        self.comboBox_4.hide()
        self.comboBox_5.hide()
        self.lineEdit_2.hide()
        self.pushButton_5.hide()
        self.label.hide()
        
        # 如果有初始条件，则添加它们
        if self.initial_conditions:
            for i, (logic, column, operator, value) in enumerate(self.initial_conditions):
                self.add_condition_with_values(logic, column, operator, value)
        else:
            # 默认添加两行条件
            self.add_condition()  # 第一行没有逻辑关系
            self.add_condition('AND')  # 第二行开始有逻辑关系
            
    def add_condition_with_values(self, logic, column, operator, value):
        """根据给定的值添加查询条件
        
        Args:
            logic: 逻辑关系，'AND' 或 'OR'
            column: 列名
            operator: 操作符
            value: 值
        """
        self.add_condition(logic, column, operator, value)
    
    def add_condition(self, logic='AND', column=None, operator=None, value=None):
        """添加查询条件"""
        # 计算新行的位置
        row = len(self.condition_widgets)
        
        # 创建控件
        combo_logic = None
        if len(self.condition_widgets) > 0:  # 第一行不需要逻辑关系
            combo_logic = QComboBox()
            combo_logic.addItems(['AND', 'OR'])
            if logic in ['AND', 'OR']:
                combo_logic.setCurrentText(logic)
            combo_logic.setObjectName(f"combo_logic_{len(self.condition_widgets)}")
        
        combo_column = QComboBox()
        combo_column.addItems(self.columns)
        if column and column in self.columns:
            combo_column.setCurrentText(column)
        combo_column.setObjectName(f"combo_column_{len(self.condition_widgets)}")
        
        combo_operator = QComboBox()
        operators = ["等于", "包含", "大于", "小于", "大于等于", "小于等于"]
        combo_operator.addItems(operators)
        if operator and operator in operators:
            combo_operator.setCurrentText(operator)
        combo_operator.setObjectName(f"combo_operator_{len(self.condition_widgets)}")
        
        line_edit = QLineEdit()
        if value:
            line_edit.setText(str(value))
        line_edit.setObjectName(f"line_edit_{len(self.condition_widgets)}")

        delete_btn = QPushButton("删除")
        delete_btn.setObjectName(f"delete_btn_{len(self.condition_widgets)}")

        # 使用唯一标识符连接信号
        delete_btn.clicked.connect(self.make_delete_callback(len(self.condition_widgets)))
        
        # 如果是第一行（索引为0），禁用删除按钮
        if len(self.condition_widgets) == 0:
            delete_btn.setEnabled(False)
            delete_btn.setStyleSheet("color: gray;")
        else:
            delete_btn.setEnabled(True)
            delete_btn.setStyleSheet("")
            delete_btn.setStyleSheet("/* 删除按钮（红色突出） */"
                                     "QPushButton {"
                                     "    background-color: #F53F3F;"
                                     "    color: white;"
                                     "}"
                                     "QPushButton:hover {"
                                     "    background-color: #D92929;"
                                     "}")
        
        # 添加到布局
        if combo_logic:
            self.gridLayout.addWidget(combo_logic, row, 0, 1, 1)
        elif 0 == row:
            self.gridLayout.addWidget(QLabel('并列选择'), 0, 0, 1, 1)
        self.gridLayout.addWidget(combo_column, row, 1, 1, 1)
        self.gridLayout.addWidget(combo_operator, row, 2, 1, 1)
        self.gridLayout.addWidget(line_edit, row, 3, 1, 1)
        self.gridLayout.addWidget(delete_btn, row, 4, 1, 1)
        
        # 保存控件引用
        widgets = (combo_logic, combo_column, combo_operator, line_edit, delete_btn)
        self.condition_widgets.append(widgets)
        
        # 调整对话框大小
        self.update_dialog_size()
    
    def make_delete_callback(self, index):
        """创建删除回调函数，避免lambda闭包问题"""
        return lambda: self.delete_condition(index)
    
    def delete_condition(self, index):
        """删除指定行的查询条件
        
        Args:
            index: 要删除的条件索引
        """
        if 0 <= index < len(self.condition_widgets):
            # 获取控件
            widgets = self.condition_widgets[index]
            combo_logic, combo_column, combo_operator, line_edit, delete_btn = widgets
            
            # 从布局中移除控件
            if combo_logic:
                self.gridLayout.removeWidget(combo_logic)
                combo_logic.deleteLater()
            self.gridLayout.removeWidget(combo_column)
            self.gridLayout.removeWidget(combo_operator)
            self.gridLayout.removeWidget(line_edit)
            self.gridLayout.removeWidget(delete_btn)
            
            # 删除控件
            combo_column.deleteLater()
            combo_operator.deleteLater()
            line_edit.deleteLater()
            delete_btn.deleteLater()
            
            # 从列表中移除
            self.condition_widgets.pop(index)
            
            # 重新排列剩余的行
            self.rearrange_conditions()
            
            # 调整对话框大小
            self.update_dialog_size()
    
    def rearrange_conditions(self):
        """重新排列条件行"""
        # 重新添加控件
        for i, widgets in enumerate(self.condition_widgets):
            combo_logic, combo_column, combo_operator, line_edit, delete_btn = widgets
            
            # 计算行位置
            row = i
            
            # 更新对象名称
            if combo_logic:
                combo_logic.setObjectName(f"combo_logic_{i}")
            combo_column.setObjectName(f"combo_column_{i}")
            combo_operator.setObjectName(f"combo_operator_{i}")
            line_edit.setObjectName(f"line_edit_{i}")
            delete_btn.setObjectName(f"delete_btn_{i}")
            
            # 如果是第一行，禁用删除按钮；否则启用
            if i == 0:
                delete_btn.setEnabled(False)
                delete_btn.setStyleSheet("color: gray;")
            else:
                delete_btn.setEnabled(True)
                delete_btn.setStyleSheet("")
                delete_btn.setStyleSheet("/* 删除按钮（红色突出） */"
                                         "QPushButton {"
                                         "    background-color: #F53F3F;"
                                         "    color: white;"
                                         "}"
                                         "QPushButton:hover {"
                                         "    background-color: #D92929;"
                                         "}")
            
            # 重新添加到布局
            if combo_logic:
                self.gridLayout.addWidget(combo_logic, row, 0, 1, 1)
            elif 0 == row:
                self.gridLayout.addWidget(QLabel('并列选择'), 0, 0, 1, 1)
            self.gridLayout.addWidget(combo_column, row, 1, 1, 1)
            self.gridLayout.addWidget(combo_operator, row, 2, 1, 1)
            self.gridLayout.addWidget(line_edit, row, 3, 1, 1)
            self.gridLayout.addWidget(delete_btn, row, 4, 1, 1)
    
    def clear_conditions(self):
        """清空所有查询条件"""
        # 删除所有条件行
        for i in reversed(range(len(self.condition_widgets))):
            # 获取控件
            widgets = self.condition_widgets[i]
            combo_logic, combo_column, combo_operator, line_edit, delete_btn = widgets
            
            # 从布局中移除控件
            if combo_logic:
                self.gridLayout.removeWidget(combo_logic)
                combo_logic.deleteLater()
            self.gridLayout.removeWidget(combo_column)
            self.gridLayout.removeWidget(combo_operator)
            self.gridLayout.removeWidget(line_edit)
            self.gridLayout.removeWidget(delete_btn)
            
            # 删除控件
            combo_column.deleteLater()
            combo_operator.deleteLater()
            line_edit.deleteLater()
            delete_btn.deleteLater()
        
        # 清空列表
        self.condition_widgets.clear()
        
        # 添加两个默认条件行
        self.add_condition()  # 第一行没有逻辑关系
        self.add_condition('AND')  # 第二行开始有逻辑关系
    
    def update_dialog_size(self):
        """更新对话框大小以适应内容"""
        # 计算所需高度
        # 基础高度(按钮、边距等) + 条件行数 * 每行高度
        base_height = 180  # 基础高度包括按钮、边距等
        row_height = 20    # 每行条件的高度
        condition_count = len(self.condition_widgets)
        
        # 计算新高度
        new_height = base_height + condition_count * row_height
        
        # 限制高度在合理范围内
        new_height = max(220, min(600, new_height))
        
        # 调整窗口大小
        self.resize(self.width(), new_height)
    
    def get_query_conditions(self):
        """获取查询条件
        
        Returns:
            条件列表 [(逻辑关系, 列名, 操作符, 值), ...]
        """
        conditions = []
        
        for widgets in self.condition_widgets:
            combo_logic, combo_column, combo_operator, line_edit, _ = widgets
            
            logic = combo_logic.currentText() if combo_logic else None
            column = combo_column.currentText()
            operator = combo_operator.currentText()
            value = line_edit.text()
            
            if value:  # 只添加有值的条件
                if logic is not None:
                    conditions.append((logic, column, operator, value))
                else:
                    # 第一个条件没有逻辑关系
                    conditions.append((column, operator, value))
        
        return conditions


class ColumnSelectionDialog(QDialog, Ui_DialogColumnSelection):
    """列选择对话框，用于控制表格中显示的列"""
    
    def __init__(self, columns, visible_columns=None, parent=None):
        """初始化列选择对话框
        
        Args:
            columns: 列名列表
            visible_columns: 当前可见的列索引列表，如果为None则默认全部可见
            parent: 父控件
        """
        super(ColumnSelectionDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.columns = columns
        # 如果没有指定可见列索引，则默认全部可见
        if visible_columns is None:
            self.visible_columns = list(range(len(columns)))
        else:
            self.visible_columns = visible_columns
        
        self.init_ui()
    
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口属性
        self.setWindowTitle("选择显示列")
        self.setMinimumWidth(300)
        
        # 设置统一字体
        font = QFont("Microsoft YaHei", 10)
        self.setFont(font)

        # 连接按钮信号
        self.pushButton.clicked.connect(self.select_all)
        self.pushButton_2.clicked.connect(self.deselect_all)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        # 移除设计器中的固定行控件，但保留布局结构
        # 清除scrollAreaWidgetContents中的示例复选框
        for i in reversed(range(self.verticalLayout_2.count())): 
            item = self.verticalLayout_2.takeAt(i)
            widget = item.widget()
            if widget:
                widget.setParent(None)
                widget.deleteLater()
        
        # 创建复选框
        self.checkboxes = []
        
        # 添加实际的复选框
        for index, column in enumerate(self.columns):
            checkbox = QCheckBox(str(column))
            checkbox.setFont(font)
            # 默认勾选当前可见的列
            checkbox.setChecked(index in self.visible_columns)
            self.checkboxes.append((index, checkbox))
            self.verticalLayout_2.addWidget(checkbox)
    
    def select_all(self):
        """全选所有列"""
        for _, checkbox in self.checkboxes:
            checkbox.setChecked(True)
    
    def deselect_all(self):
        """取消全选所有列"""
        for _, checkbox in self.checkboxes:
            checkbox.setChecked(False)
    
    def get_selected_columns(self):
        """获取选中的列索引
        
        Returns:
            选中的列索引列表
        """
        selected_columns = []
        for index, checkbox in self.checkboxes:
            if checkbox.isChecked():
                selected_columns.append(index)
        
        # 确保至少有一列被选中
        if not selected_columns and self.checkboxes:
            selected_columns.append(0)
        
        return selected_columns


class RecordFormDialog(QDialog, Ui_DialogRecordForm):
    """数据记录表单对话框，用于添加或编辑记录"""
    
    def __init__(self, table_model, record=None, parent=None):
        """初始化记录表单对话框
        
        Args:
            table_model: 表格模型，用于获取字段信息
            record: 要编辑的记录，如果为None则为添加新记录
            parent: 父控件
        """
        super(RecordFormDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.table_model = table_model
        self.record = record# if record else self.table_model.record()
        self.field_widgets = {}  # 存储字段控件
        
        # 立即设置窗口标题
        title = "编辑记录" if self.record else "添加记录"
        self.setWindowTitle(title)
        
        self.init_ui()
        
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口属性
        self.setMinimumWidth(400)
        
        # 设置统一字体
        font = QFont("Microsoft YaHei", 10)
        self.setFont(font)
        
        # 连接按钮信号
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        
        # 移除设计器中的固定行控件，但保留布局结构
        # 清除formLayout中的示例控件
        for i in reversed(range(self.formLayout.count())): 
            item = self.formLayout.takeAt(i)
            widget = item.widget()
            if widget:
                widget.setParent(None)
                widget.deleteLater()
        
        # 根据表结构生成表单字段
        for i in range(self.table_model.columnCount()):
            field = self.table_model.record().field(i)
            field_name = field.name()
            display_name = self.table_model.headerData(i, Qt.Horizontal)
            
            # 跳过自增主键字段
            if field.isAutoValue():
                continue
                
            # 创建字段控件
            field_widget = self._create_field_widget(field)
            field_widget.setFont(font)
            
            # 如果是编辑模式，设置当前值
            if self.record:
                # 从传入的record对象中获取字段值
                record_field_value = self.record.value(field_name)
                if record_field_value is not None and not self.record.isNull(field_name):
                    self._set_field_value(field_widget, field)
                
            # 添加到表单布局
            label = QLabel(f"{display_name}:")
            label.setFont(font)
            self.formLayout.addRow(label, field_widget)
            
            # 保存字段控件引用
            self.field_widgets[field_name] = field_widget
            
        # 设置特定控件的样式，而不是整个对话框
        # 为所有QLineEdit控件设置样式
        line_edits = self.findChildren(QLineEdit)
        for line_edit in line_edits:
            line_edit.setStyleSheet("""
                min-height: 25px; 
                border: 1px solid #E5E6EB;
                border-radius: 4px;
                padding: 4px 8px;
                background-color: white;
                font-size: 13px;
            """)
            line_edit.setMinimumWidth(200)
            
        # 为所有QCheckBox控件设置样式
        checkboxes = self.findChildren(QCheckBox)
        for checkbox in checkboxes:
            checkbox.setStyleSheet("""
                QCheckBox { 
                    spacing: 5px;
                }
            """)
            
        # 为所有日期时间控件设置样式（与QLineEdit保持一致）
        date_edits = self.findChildren(QDateEdit)
        time_edits = self.findChildren(QTimeEdit)
        datetime_edits = self.findChildren(QDateTimeEdit)
        
        # 日期时间控件的通用样式
        datetime_style = """
            QDateEdit, QTimeEdit, QDateTimeEdit {
                min-height: 25px; 
                border: 1px solid #E5E6EB;
                border-radius: 4px;
                padding: 4px 8px;
                background-color: white;
                font-size: 13px;
                padding-left: 5px;
            }
            
            QDateEdit::drop-down, QTimeEdit::drop-down, QDateTimeEdit::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 20px;
                border-left: 1px solid #E5E6EB;
                border-top-right-radius: 3px;
                border-bottom-right-radius: 3px;
            }
            
            QDateEdit::down-arrow, QTimeEdit::down-arrow, QDateTimeEdit::down-arrow {
                image: url(:/icons/pictures/Expand.png);
                width: 12px;
                height: 12px;
            }
            
            /* 日历控件样式 */
            QCalendarWidget QWidget {
                alternate-background-color: #f0f0f0;
            }
            
            QCalendarWidget QAbstractItemView:enabled {
                font-size: 12px;
                color: #333333;
                background-color: white;
                selection-background-color: #40BFFF;
                selection-color: white;
            }
            
            QCalendarWidget QAbstractItemView:disabled {
                color: #999999;
            }
            
            QCalendarWidget QSpinBox {
                font-size: 12px;
            }
            
            QCalendarWidget QSpinBox::up-button {
                subcontrol-origin: border;
                subcontrol-position: top right;
            }
            
            QCalendarWidget QSpinBox::down-button {
                subcontrol-origin: border;
                subcontrol-position: bottom right;
            }
            
            /* 年份和月份下拉框样式 */
            QCalendarWidget QToolButton {
                color: #333333;
                background-color: transparent;
                border: none;
                font-size: 12px;
            }
            
            QCalendarWidget QToolButton:hover {
                background-color: #e0e0e0;
                border-radius: 2px;
            }
            
            QCalendarWidget QMenu {
                background-color: white;
                border: 1px solid #cccccc;
            }
            
            QCalendarWidget QMenu::item {
                color: #333333;
                padding: 4px 12px;
            }
            
            QCalendarWidget QMenu::item:selected {
                background-color: #40BFFF;
                color: white;
            }
        """
        
        for date_edit in date_edits:
            date_edit.setStyleSheet(datetime_style)
            date_edit.setMinimumWidth(200)
            # 启用日历弹窗
            date_edit.setCalendarPopup(True)
            
        for time_edit in time_edits:
            time_edit.setStyleSheet(datetime_style)
            time_edit.setMinimumWidth(200)
            
        for datetime_edit in datetime_edits:
            datetime_edit.setStyleSheet(datetime_style)
            datetime_edit.setMinimumWidth(200)
            # 启用日历弹窗
            datetime_edit.setCalendarPopup(True)
    
    def _create_field_widget(self, field):
        """根据字段类型创建对应的控件
        
        Args:
            field: 字段对象
        
        Returns:
            创建的控件
        """
        field_type = field.type()
        field_name = field.name()
        
        # 特殊处理某些字段，确保它们始终是文本输入框
        # wells表中的井名(well_name)、位置(location)、备注(notes)字段应始终为文本类型
        # mechanical_analysis表中的分析类型(analysis_type)字段应始终为文本类型
        text_fields = ['well_name', 'location', 'notes', 'analysis_type']
        if field_name in text_fields:
            widget = QLineEdit()
            widget.setMinimumWidth(200)
        # 根据字段类型创建不同的控件
        elif field_type in [2, 3, 4, 6]:  # 整数和浮点数类型
            widget = QLineEdit()
            widget.setValidator(QDoubleValidator() if field_type in [3, 6] else QIntValidator())
            widget.setMinimumWidth(200)
        elif field_type == 1:  # 布尔类型
            widget = QCheckBox()
        elif field_type == 10:  # 日期类型
            widget = QDateEdit()
            widget.setCalendarPopup(True)
            widget.setDate(QDate.currentDate())
            widget.setMinimumWidth(200)
        elif field_type == 11:  # 时间类型
            widget = QTimeEdit()
            widget.setTime(QTime.currentTime())
            widget.setMinimumWidth(200)
        elif field_type == 12:  # 日期时间类型
            widget = QDateTimeEdit()
            widget.setCalendarPopup(True)
            widget.setDateTime(QDateTime.currentDateTime())
            widget.setMinimumWidth(200)
        else:  # 默认为文本类型
            widget = QLineEdit()
            widget.setMinimumWidth(200)
            
        # 设置必填字段的样式
        if not field.isNull() and not field.defaultValue().isValid():
            widget.setStyleSheet("border: 1px solid red;")
            widget.setToolTip("此字段为必填项")
            
        return widget
        
    def _set_field_value(self, widget, field):
        """设置控件的值
        
        Args:
            widget: 控件
            field: 字段对象
        """
        value = self.record.value(field.name())
        
        if isinstance(widget, QLineEdit):
            widget.setText(str(value) if value is not None else "")
        elif isinstance(widget, QCheckBox):
            widget.setChecked(bool(value))
        elif isinstance(widget, QDateEdit):
            widget.setDate(value if isinstance(value, QDate) else QDate.fromString(str(value), "yyyy-MM-dd"))
        elif isinstance(widget, QTimeEdit):
            widget.setTime(value if isinstance(value, QTime) else QTime.fromString(str(value), "hh:mm:ss"))
        elif isinstance(widget, QDateTimeEdit):
            widget.setDateTime(value if isinstance(value, QDateTime) else QDateTime.fromString(str(value), "yyyy-MM-dd hh:mm:ss"))
            
    def get_record(self):
        """获取表单数据
        
        Returns:
            包含表单数据的记录对象
        """
        # 创建新记录
        record = self.table_model.record()
        
        # 设置字段值
        for field_name, widget in self.field_widgets.items():
            field_index = record.indexOf(field_name)
            field = record.field(field_index)
            
            # 根据控件类型获取值
            if isinstance(widget, QLineEdit):
                value = widget.text()
                if not value and not field.isNull():
                    # 必填字段为空，返回None表示验证失败
                    widget.setFocus()
                    return None
                record.setValue(field_name, value)
            elif isinstance(widget, QCheckBox):
                record.setValue(field_name, widget.isChecked())
            elif isinstance(widget, QDateEdit):
                record.setValue(field_name, widget.date().toString("yyyy-MM-dd"))
            elif isinstance(widget, QTimeEdit):
                record.setValue(field_name, widget.time().toString("hh:mm:ss"))
            elif isinstance(widget, QDateTimeEdit):
                record.setValue(field_name, widget.dateTime().toString("yyyy-MM-dd hh:mm:ss"))
                
        return record


class PlotDialog(QDialog):
    """绘图对话框"""

    def __init__(self, parent=None):
        super(PlotDialog, self).__init__(parent)
        self.setWindowTitle("选择绘图类型")
        self.resize(300, 200)

        # 设置布局
        layout = QVBoxLayout(self)

        # 添加说明标签
        label = QLabel("请选择要绘制的图形类型：")
        layout.addWidget(label)

        # 创建单选按钮组
        self.plot_type_group = QButtonGroup(self)

        # 原始数据折线图
        self.radio_original = QRadioButton("1、原始数据折线图")
        self.plot_type_group.addButton(self.radio_original, 1)
        layout.addWidget(self.radio_original)

        # 三次样条平滑折线图
        self.radio_smoothed = QRadioButton("2、三次样条函数最小二乘法平滑后的数据折线图")
        self.plot_type_group.addButton(self.radio_smoothed, 2)
        layout.addWidget(self.radio_smoothed)

        # 默认选择原始数据
        self.radio_original.setChecked(True)

        # 添加按钮盒
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

    def get_selected_plot_type(self):
        """获取选择的绘图类型"""
        return self.plot_type_group.checkedId()


class WellManagerDialog(QDialog):
    """油井管理对话框 - 整合打开、删除和重命名功能"""

    def __init__(self, parent=None, well_data=None, current_well=None):
        super().__init__(parent)
        self.well_data = well_data or {}
        self.current_well = current_well
        self.selected_well = None
        self.action = None  # 'open', 'rename', 'delete'
        self.new_name = None
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("油井管理")
        self.setMinimumSize(700, 500)

        layout = QVBoxLayout()

        # 标题和说明
        title_label = QLabel("油井数据管理")
        title_label.setStyleSheet("font-size: 16px; font-weight: bold;")
        layout.addWidget(title_label)

        # 使用分割器创建左右布局
        splitter = QSplitter(Qt.Horizontal)

        # 左侧油井列表和操作按钮
        left_widget = QWidget()
        left_layout = QVBoxLayout()

        # 油井列表
        list_group = QGroupBox("油井列表")
        list_layout = QVBoxLayout()
        self.well_list = QListWidget()
        self.well_list.currentItemChanged.connect(self.on_well_selected)
        list_layout.addWidget(self.well_list)
        list_group.setLayout(list_layout)
        left_layout.addWidget(list_group)

        # 操作按钮
        btn_group = QGroupBox("操作")
        btn_layout = QVBoxLayout()

        self.open_btn = QPushButton("打开选中油井")
        self.rename_btn = QPushButton("重命名选中油井")
        self.delete_btn = QPushButton("删除选中油井")

        self.open_btn.clicked.connect(lambda: self.perform_action('open'))
        self.rename_btn.clicked.connect(lambda: self.perform_action('rename'))
        self.delete_btn.clicked.connect(lambda: self.perform_action('delete'))

        btn_layout.addWidget(self.open_btn)
        btn_layout.addWidget(self.rename_btn)
        btn_layout.addWidget(self.delete_btn)

        btn_group.setLayout(btn_layout)
        left_layout.addWidget(btn_group)

        left_widget.setLayout(left_layout)

        # 右侧油井数据展示
        right_widget = QWidget()
        right_layout = QVBoxLayout()

        data_group = QGroupBox("油井数据详情")
        data_layout = QVBoxLayout()
        self.data_display = QTextEdit()
        self.data_display.setReadOnly(True)
        data_layout.addWidget(self.data_display)
        data_group.setLayout(data_layout)
        right_layout.addWidget(data_group)

        right_widget.setLayout(right_layout)

        splitter.addWidget(left_widget)
        splitter.addWidget(right_widget)
        splitter.setSizes([300, 400])

        layout.addWidget(splitter)

        # 底部按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Close)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

        self.setLayout(layout)

        # 填充油井列表并设置当前选中项
        self.populate_well_list()

        # 初始按钮状态
        self.update_button_states()

    def populate_well_list(self):
        self.well_list.clear()
        for well_name in self.well_data.keys():
            self.well_list.addItem(well_name)

        # 如果有当前油井，选中它
        if self.current_well and self.current_well in self.well_data:
            items = self.well_list.findItems(self.current_well, Qt.MatchExactly)
            if items:
                self.well_list.setCurrentItem(items[0])

    def on_well_selected(self, current, previous):
        if current:
            well_name = current.text()
            self.selected_well = well_name
            well_data = self.well_data.get(well_name, {})

            # 格式化显示数据
            display_text = f"油井名称: {well_name}\n\n参数:\n"
            for key, value in well_data.items():
                if key != "油井名称":  # 不重复显示油井名称
                    display_text += f"{key}: {value}\n"

            self.data_display.setText(display_text)

        self.update_button_states()

    def update_button_states(self):
        """根据选中状态更新按钮可用性"""
        has_selection = self.selected_well is not None
        self.open_btn.setEnabled(has_selection)
        self.rename_btn.setEnabled(has_selection)
        self.delete_btn.setEnabled(has_selection)

    def perform_action(self, action_type):
        """执行操作"""
        if not self.selected_well:
            QMessageBox.warning(self, "警告", "请先选择一个油井!")
            return

        self.action = action_type

        if action_type == 'open':
            self.accept()
        elif action_type == 'rename':
            self.rename_well()
        elif action_type == 'delete':
            self.delete_well()

    def rename_well(self):
        """重命名选中的油井"""
        new_name, ok = QInputDialog.getText(
            self, "重命名油井", "请输入新名称:", text=self.selected_well
        )
        if ok and new_name:
            new_name = new_name.strip()
            if not new_name:
                QMessageBox.warning(self, "警告", "油井名称不能为空!")
                return
            if new_name == self.selected_well:
                QMessageBox.warning(self, "警告", "新名称与当前名称相同!")
                return
            if new_name in self.well_data:
                QMessageBox.warning(self, "警告", f"油井 '{new_name}' 已存在!")
                return
            # 更新数据
            self.well_data[new_name] = self.well_data[self.selected_well]
            self.well_data[new_name]["油井名称"] = new_name
            del self.well_data[self.selected_well]
            # 更新当前选中项
            if self.current_well == self.selected_well:
                self.current_well = new_name
            self.selected_well = new_name
            # 刷新列表
            self.populate_well_list()
            QMessageBox.information(self, "成功", f"油井已重命名为: {new_name}")

    def delete_well(self):
        """删除选中的油井"""
        reply = QMessageBox.question(
            self, "确认删除",
            f"确定要删除油井 '{self.selected_well}' 吗?",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            # 从数据中删除
            del self.well_data[self.selected_well]

            # 更新当前选中项
            if self.current_well == self.selected_well:
                self.current_well = None

            self.selected_well = None

            # 刷新列表
            self.populate_well_list()
            self.data_display.clear()

            QMessageBox.information(self, "成功", "油井已删除!")
